package cn.wolfcode.mp.web.controller;

import cn.wolfcode.mp.domain.Employee;
import cn.wolfcode.mp.query.JsonResult;
import cn.wolfcode.mp.service.IEmployeeService;
import cn.wolfcode.mp.service.IPermissionService;
import cn.wolfcode.mp.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登录操作
 */
@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    // 登陆
    @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session){
        try {
            Employee employee = employeeService.login(username,password);
            // 把用户信息存到session
            // session.setAttribute("USER_IN_SESSION",employee);
            // 抽工具类,使用调用方法
            UserContext.setCurrentUser(employee);
            // 如果不是超管,才查询
            if (!employee.isAdmin()){
                // 查询该用户拥有的权限信息(权限表达式集合)
                List<String> stringList = permissionService.selectByEmpId(employee.getId());
                // 把权限信息存到session中
                // session.setAttribute(UserContext.PERMISSION_IN_SESSION,stringList);
                UserContext.setPermissions(stringList);
            }
            return new JsonResult(true,"登陆成功");
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }

    // 注销
    @RequestMapping("/userLogout")
    public String logout(HttpSession session){
        //销毁session会话
        session.invalidate();
        return "redirect:/login.html";
    }

    // 跳转修改密码页面
    @RequestMapping("/redirectPwd")
    public String redirectPwd(){
        return "/updatePwd";
    }


    // 重定向到错误页面
    @RequestMapping("/nopermission")
    public String nopermission(){
        return "common/nopermission";
    }
}
